Page({
  data: {
    phone: '',
    remark: '',
    addressId: '',
    bookId: '',
    cloud: null
  },

  onLoad(options) {
    this.initSharedCloud();
    if (options.id) {
      this.setData({ addressId: options.id });
      this.loadAddress();
    }
    if (options.bookId) {
      this.setData({ bookId: options.bookId });
    }
  },

  async initSharedCloud() {
    const cloud = new wx.cloud.Cloud({
      resourceAppid: 'wx3199c80279c7b8c3',
      resourceEnv: 'education-6gwexwp8488514df'
    });
    
    try {
      await cloud.init();
      this.setData({ cloud });
    } catch (err) {
      console.error('初始化云环境失败：', err);
    }
  },

  async loadAddress() {
    try {
      const { cloud, addressId } = this.data;
      const db = cloud.database();
      const { data } = await db.collection('addresses').doc(addressId).get();
      
      this.setData({
        phone: data.phone,
        remark: data.remark
      });
    } catch (err) {
      console.error('加载地址失败：', err);
    }
  },

  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    });
  },

  async handleSave() {
    const { phone, remark, addressId, bookId, cloud } = this.data;
    
    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }

    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return;
    }

    try {
      const db = cloud.database();
      const userInfo = getApp().globalData.userInfo;
      
      const addressData = {
        phone,
        remark,
        userId: userInfo._id,
        updateTime: db.serverDate()
      };

      if (addressId) {
        // 更新地址
        await db.collection('addresses').doc(addressId).update({
          data: addressData
        });
      } else {
        // 新增地址
        addressData.createTime = db.serverDate();
        const res = await db.collection('addresses').add({
          data: addressData
        });

        // 如果是从书籍详情页添加地址，则同时创建书籍地址关联
        if (bookId) {
          await db.collection('bookAddresses').add({
            data: {
              bookId,
              addressId: res._id,
              userId: userInfo._id,
              createTime: db.serverDate()
            }
          });
        }
      }

      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 1500);

    } catch (err) {
      console.error('保存地址失败：', err);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'error'
      });
    }
  }
}); 